package com.example.modulepicselector.adapter;

import android.database.Cursor;
import android.provider.MediaStore;

import androidx.recyclerview.widget.RecyclerView;

public abstract class RecyclerViewCursorAdapter<VH extends RecyclerView.ViewHolder> extends
        RecyclerView.Adapter<VH> {

    private Cursor mCursor;
    private int mRowIDColumn;

    RecyclerViewCursorAdapter(Cursor c) {
        setHasStableIds(true);
        swapCursor(c);
    }

    protected abstract void onBindViewHolder(VH holder, Cursor cursor,int position);

    @Override
    public void onBindViewHolder(VH holder, int position) {
        if (!isDataValid(mCursor)) {
            throw new IllegalStateException("当游标处于无效状态时，无法绑定视图持有者");
        }
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException(" \n" +
                    "无法将光标移动到位置 " + position
                    + " 在尝试绑定视图持有者时\n" +
                    "\n");
        }

        onBindViewHolder(holder, mCursor,position);
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

/*    @Override
    public int getItemViewType(int position) {
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException("无法将光标移动到位置\n" +
                    "\n " + position
                    + " 当试图获取项目视图类型时。\n" +
                    "\n");
        }
        return getItemViewType(position, mCursor);
    }

    protected abstract int getItemViewType(int position, Cursor cursor);*/

    @Override
    public int getItemCount() {
        if (isDataValid(mCursor)) {


            return mCursor.getCount();
        } else {
            return 0;
        }
    }

    @Override
    public long getItemId(int position) {

        if (!isDataValid(mCursor)) {
            throw new IllegalStateException("无法在游标处于无效状态时查找项标识。\n" +
                    "\n");
        }
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException("无法将光标移动到位置\n" +
                    "\n " + position
                    + " 当我们试图得到物品的身份时\n" +
                    "\n");
        }

        return mCursor.getLong(mRowIDColumn);
    }

    public void swapCursor(Cursor newCursor) {

        if (newCursor == mCursor) {
            return;
        }

        if (newCursor != null) {

            mCursor = newCursor;
            mRowIDColumn = mCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
            notifyDataSetChanged();
        } else {
            notifyItemRangeRemoved(0, getItemCount());
            mCursor = null;
            mRowIDColumn = -1;
        }
    }

    public Cursor getCursor() {
        return mCursor;
    }

    private boolean isDataValid(Cursor cursor) {
        return cursor != null && !cursor.isClosed();
    }
}
